/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package apus.action.user;

import apus.action.Action;
import apus.action.ActionResult;
import apus.entity.User;
import apus.persistence.UserDAO;
import apus.persistence.jdbc.AbstractJdbcDAO;
import apus.services.ServiceLocator;
import java.io.UnsupportedEncodingException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author 21vek
 */
public class UserSaveAction implements Action {

    @Override
    public String getName() {
        return "user.save";
    }

    @Override
    public ActionResult execute(HttpServletRequest request, HttpServletResponse response) {

        try {
            request.setCharacterEncoding("UTF-8");
        } catch (UnsupportedEncodingException ex) {
        }

        // if Save button have been pressed
        if (request.getParameter("saveButton") != null) {
            UserDAO userDAO = ServiceLocator.getService(UserDAO.class);

            User user = new User();

            // load data from request
            if (request.getParameter("login") != null) {
                user.setLogin(request.getParameter("login"));
            }

            if (request.getParameter("pass") != null) {
                user.setPassword(request.getParameter("pass"));
            }

            if (request.getParameter("role") != null) {
                user.setRole(Integer.parseInt(request.getParameter("role")));
            }

            userDAO.create(user);
            request.getSession().setAttribute("win", "New employee was successfully added");
        }
        return ActionResult.redirect("administration");
    }
}
